<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\service\WechatService;
use think\Db;
use think\Log;

/**
 * 首页接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $params = $this->request->get('');
        // Token验证 将微信转过来的数据原样返回
        if(isset($params['echostr'])) {
            echo $params['echostr'];
            exit;
        }
    }


    public function jsConfig()
    {
        $url = $this->request->get('url');
        $result = WechatService::jsConfig($url);
        Log::info(json_encode($result));
        if (!$result || empty($result['signature'])) {
            $this->error(__('获取失败'));
        }
        $this->success('', $result);
    }

    /**
     * 授权
     */
    public function authorization()
    {
        $app = WechatService::initAccount();
        $redirectUrl = $app->oauth->redirect()->getTargetUrl();
        if(!empty($redirectUrl)){
            $this->success('获取授权地址成功', ['url'=>$redirectUrl]);
        }else{
            $this->error(__('获取授权地址失败'));
        }
    }


    /**
     * 授权回调
     */
    public function oauth_callback()
    {
//        $code = $this->request->get('code');
        $param=$this->request->param();
//        var_dump($param);die;
        $code=$param['code'];
//        var_dump($code);
//        $promoter = $this->request->get('promoter');
//        if($promoter){
//            $extend['promoter'] = $promoter;
//        }else{
//            $extend = [];
//        }
//        $extend['source'] = 3;
//        if(empty($code)){
//            $this->error(__('参数错误'));
//        }


       try{
            $app = WechatService::initAccount();
            $user = $app->oauth->user()->toArray();
//            echo "<pre>";
//        var_dump($app);
//        echo '1233333333';
//        var_dump($user);die;
            //$user = $app->oauth->userFromCode($code)->toArray();
        }catch(\Exception $e){
            //Log::error('授权失败:'.$e->getMessage());
            $this->error(__('授权失败'));
        }
        if(isset($user['id']) && !empty($user['id'])){
            $user_info = \app\common\model\User::where("mp_wx_openid", "=",  $user['id'])->find();
            if($user_info){
                $this->auth->direct($user_info->id);
                $userinfo = $this->auth->getUserinfo();
                $data = [
                    'userinfo' => $userinfo
                ];
                $targetUrl = 'https://hospital.chunchuangkeji.com/h5/index.html#/pages/info/index?token='.$userinfo['token'];
//                $targetUrl = "https://www.example.com/somepage";

// 使用header函数进行跳转
                header("Location: $targetUrl");
//                $this->success(__('登录成功'), $data);
            }else{
                $extend['mp_wx_openid'] = $user['id'];
                $ret = $this->auth->register($user['name'], '','','',$extend);
                if ($ret) {
                    $data = ['userinfo' => $this->auth->getUserinfo()];
                    $targetUrl = 'https://hospital.chunchuangkeji.com/h5/index.html#/pages/info/index?token='.$data['userinfo']['token'];
//                $targetUrl = "https://www.example.com/somepage";

// 使用header函数进行跳转
                    header("Location: $targetUrl");
//                    $this->success(__('成功'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            }  
        }else{
            $this->error(__('授权失败'));
        }
        
    }

    public function name()
    {
        $param=$this->request->param();
        $res=Db::name('user')->where('id',$this->auth->id)->update($param);
        if ($res !== false) {
            $this->success('成功');
        } else {
            $this->error('失败');
        }

    }

}
